//
// [Author] lg (https://github.com/lemos1235)
// [Date] 2024/4/12
//
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;

const kPictureDisappearDuration = Duration.zero;
const kTriggerOffset = 50.0;

SpringDescription kPictureSpringBuilder({
  required IndicatorMode mode,
  required double offset,
  required double actualTriggerOffset,
  required double velocity,
}) {
  double mass = 6 + (offset - actualTriggerOffset) / 36;
  double damping = 0.75 + velocity.abs() / 10000;
  double stiffness = 1000 + velocity.abs() / 6;
  return SpringDescription(
    mass: mass,
    stiffness: stiffness,
    damping: damping,
  );
}

double kPictureFrictionFactor(double overscrollFraction) => 0.1 * math.pow(1 - overscrollFraction, 2);

class PictureHeader extends Header {
  final Key? key;

  final Widget background;

  const PictureHeader({
    this.key,
    super.triggerOffset = kTriggerOffset,
    super.clamping = false,
    super.position,
    super.spring,
    super.readySpringBuilder = kPictureSpringBuilder,
    super.springRebound = false,
    super.frictionFactor = kPictureFrictionFactor,
    super.safeArea,
    super.infiniteOffset,
    super.hitOver,
    super.infiniteHitOver,
    super.hapticFeedback,
    super.triggerWhenReleaseNoWait = true,
    required this.background,
  }) : super(
          processedDuration: kPictureDisappearDuration,
        );

  @override
  Widget build(BuildContext context, IndicatorState state) {
    assert(state.axis == Axis.vertical, 'BezierCircleHeader does not support horizontal scrolling.');
    assert(!state.reverse, 'BezierCircleHeader does not support reverse.');
    return _PictureIndicator(
      key: key,
      state: state,
      background: background,
    );
  }
}

class _PictureIndicator extends StatefulWidget {
  const _PictureIndicator({super.key, required this.state, required this.background});

  final IndicatorState state;

  final Widget background;

  @override
  State<_PictureIndicator> createState() => _PictureIndicatorState();
}

class _PictureIndicatorState extends State<_PictureIndicator> {
  @override
  Widget build(BuildContext context) {
    final state = widget.state;
    final scale = math.min(state.offset, kTriggerOffset) / kTriggerOffset;
    return Transform.scale(
      scale: 1.0 + scale,
      child: widget.background,
    );
  }
}
